<template>
    <el-card class="translate">
        <el-steps :space="200" :active="step" simple>
            <el-step title="选择项目" :icon="FolderOpened" />
            <el-step title="选择文件" :icon="FolderOpened" />
            <el-step title="识别选项" :icon="FolderOpened" />
            <el-step title="识别结果" :icon="FolderOpened" />
        </el-steps>
        <template v-if="step === 1">
            <div class="translate-drop" @click="openFolder">
                <el-icon>
                    <UploadFilled />
                </el-icon>
                <p>请选择项目</p>
            </div>
        </template>
        <template v-if="step === 2">
            <div class="translate-tree">
                <el-scrollbar>
                    <el-tree :data="folder" :props="folderProps" show-checkbox ref="treeRef" />
                </el-scrollbar>
            </div>
            <div class="translate-buttons">
                <el-button type="primary" @click="onConfirmTree">确定</el-button>
				<el-button @click="onCancelTree">返回</el-button>
            </div>
        </template>
        <template v-if="step === 3">
            <div class="translate-preview">
                <el-scrollbar>
                    <el-form :model="form" :rules="rules" label-position="left" ref="formRef">
                        <el-form-item prop="matcher" label="匹配方式">
                            <el-select v-model="form.matcher" placeholder="请选择匹配方式">
                                <el-option v-for="item in matchers" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-scrollbar>
            </div>
            <div class="translate-buttons">
				<el-button type="primary" @click="onConfirmLanguage">确定</el-button>
				<el-button @click="onCancelLanguage">返回</el-button>
			</div>
        </template>
        <template v-if="step === 4">
			<div class="translate-preview">
				<el-scrollbar>
					<div class="preview-item" v-for="item in preview" :key="item.path">
						<div class="preview-item__remark">// {{ item.path }}</div>
						<div class="preview-item__data">
							<div class="preview-item__line" v-for="(value,key) in item.data">"{{ key }}" : "{{ value }}"</div>
						</div>
                        <div class="preview-item__action" @click="onReplace(item)" v-if="item.status === 0">替换</div>
                        <div class="preview-item__action" v-if="item.status === 1">
                            <el-icon><CircleCheckFilled /></el-icon>
                        </div>
					</div>
				</el-scrollbar>
			</div>
        </template>
    </el-card>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { ElTree, FormRules, FormInstance } from 'element-plus'
import { ElNotification } from 'element-plus'
import { openDirectory, deepClone, getStoreConfig, traditionalized } from '@renderer/utils'
import { matchers } from "@renderer/service"
import { FolderOpened, UploadFilled, CircleCheckFilled  } from '@element-plus/icons-vue'

const config = ref<ApplicationStoreConfig>()
onBeforeMount(async () => {
	config.value = await getStoreConfig()
})

const step = ref<number>(1)
    function nextStep(){
	step.value ++
}

//#region 目录选择

const folder = ref<Array<IDirectory>>([])
const folderProps = { label: 'name', children: 'children'}
// 打开目录
async function openFolder(){
	const result = await openDirectory()
	if (result.canceled) return
	const path = result.filePaths[0]
	folder.value = await window.bridge.readDirectory(path, undefined, deepClone(config.value?.common.exclude ?? []))
	nextStep()
}

// #endregion


//#region 文件选择

const treeRef = ref<InstanceType<typeof ElTree>>()

const treeSelected = ref<Array<IDirectory>>([])

// 点击确定
const onConfirmTree = () => {
	const nodes = treeRef.value!.getCheckedNodes(true,true) as Array<IDirectory>
	const files = nodes.filter(item => item.type === 'file')
	if(files.length < 1){
		ElNotification.error({ title: '操作失败', message: '请选择文件' })
		return
	}
	treeSelected.value =  files
	nextStep()
}

// 点击取消
const onCancelTree = () => {
	treeSelected.value = []
	step.value --
}

//#endregion


//#region 表单填写

const form = reactive({
    matcher: ''
})

// 表单校验规则
const rules = reactive<FormRules>({
	matcher: [{required: true, message: '请选择匹配方式', trigger: 'change'}],
})

// 点击确定
const formRef = ref<FormInstance>()
const onConfirmLanguage = () => {
	formRef.value?.validate(valid => {
		if(!valid) return
		nextStep()
		getPreviewData()
	})
}

// 点击返回
const onCancelLanguage = () => {
	step.value --
	form.matcher = ''
}
//#endregion


//#region 数据预览

interface SimpledPacketData extends PacketData{
    fullPath: string,
    status: 0 | 1 | 2
}

const preview = ref<Array<SimpledPacketData>>([])
async function getPreviewData(){
    const matcher = Object.values(matchers).find(matcher => matcher.id === form.matcher)!
    for(let item of treeSelected.value){
        const content = await window.bridge.readFile(item.path)
        const matched = matcher.match(content)
        const filterMatched = matched.filter(item => {
            return traditionalized(item) !== item
		})
        const packet = packetData(filterMatched, item.relative, item.path)
		if(Object.keys(packet.data).length > 0) preview.value.push(packet)
    }
}

// 数据结构包装
const packetData = (matched: Array<string>, path: string, fullPath: string) : SimpledPacketData => {
	const data:Record<string, string> = {}
	for(let key of matched){ data[key] = traditionalized(key) }
	return { path, data, fullPath, status: 0 }
}

// #endregion


// #region 文件替换
async function onReplace(item: SimpledPacketData){
    const { fullPath, data } = item
    const matcher = Object.values(matchers).find(matcher => matcher.id === form.matcher)!
    const content = await window.bridge.readFile(fullPath)
    const replaced = matcher.replace(content, data)
    try{
        await window.bridge.writeFile(fullPath, replaced)
        ElNotification.success({ message:'写入成功', title: '操作成功'})
        item.status = 1
    }catch(e){
        const { message } = e as Error
        ElNotification.error({ message, title: '写入失败'})
    }
}




// #endregion
</script>

<style lang="scss" scoped>
@use '../Translate/translate.scss'
</style>
